//
//  ETSalaryCalculationAlertController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/11/3.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class ETSalaryCalculationAlertController: UIViewController {
    
    fileprivate var coverView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        return view
    }()
    
    fileprivate var panelView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = 6
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOpacity = 0.3
        view.layer.shadowOffset = CGSize(width: 1, height: 1)
        view.backgroundColor = UIColor.white
        return view
    }()
    
    fileprivate var titleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .center
        label.font = UIFont(name: "PingFangSC-Regular", size: 24)
        label.text = "工资结算啦！"
        return label
    }()
    
    fileprivate var preferredMoneyLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont(name: "PingFangSC-Regular", size: 18)
        label.numberOfLines = 0
        return label
    }()
    
    fileprivate var actualMoneyLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont(name: "PingFangSC-Regular", size: 18)
        label.numberOfLines = 0
        label.text = "约定工资为：3800元111111111111111111111111/n"
        return label
    }()
    
//    fileprivate var reasonLabel: UILabel = {
//        let label = UILabel()
//        label.font = UIFont(name: "PingFangSC-Regular", size: 18)
//        label.textColor = UIColor.mg_lightGray
//        label.numberOfLines = 0
//        label.text = "工资扣除原因：你把工地的机器弄坏了/nsss"
//        return label
//    }()
    
    fileprivate var okButton: UIButton = {
        let button = UIButton()
        button.setTitleColor(UIColor.mg_blue, for: .normal)
        button.setTitle("确定", for: .normal)
        return button
    }()
    
    private var okHandler: (()->Void)?
    
    private var preferredMoney: String?
    private var actualMoney: String?
    private var reason: String?
    
    //当前alert是否正在显示
    private var isShowing:Bool = false
    
    //preferredMoneyLabel显示的内容
    private var preferredMoneyLabelString: NSMutableAttributedString {
        get {
            let mutableAttributedString = NSMutableAttributedString(string: "约定结算工资为：    ")
            var money: String!
            if self.preferredMoney != nil && Tool.numberToMoney(self.preferredMoney!) != nil{
                money = Tool.numberToMoney(self.preferredMoney!)! + "元"
            }
            else {
                money = "--元"
            }
            let aString = NSMutableAttributedString(string: money, attributes: [NSAttributedStringKey.foregroundColor: UIColor.mg_blue])
            mutableAttributedString.append(aString)
            return mutableAttributedString
        }
    }
    
    //actualMoneyLabel显示的内容
    private var actualMoneyLabelString: NSMutableAttributedString {
        get {
            let mutableAttributedString = NSMutableAttributedString(string: "此次实际结算工资为：")
            var money: String!
            if self.actualMoney != nil && Tool.numberToMoney(self.actualMoney!) != nil{
                money = Tool.numberToMoney(self.actualMoney!)! + "元"
            }
            else {
                money = "--元"
            }
            let aString = NSMutableAttributedString(string: money, attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
            mutableAttributedString.append(aString)
            return mutableAttributedString
        }
    }
    
    //reasonLabel显示内容
    private var reasonLabelString: String {
        get  {
            var aString = "工资扣除原因："
            aString += self.reason ?? ""
            return aString
        }
    }
    
    init (_  okHandler: @escaping ()-> Void){
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.okHandler = okHandler
    }
    
    init(dict: [String: Any]) {
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.analysis(dict)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.okButton.addTarget(self, action: #selector(doOkButtonAction), for: .touchUpInside)
        
        self.setupViews()
        self.updateViews()
        
        self.isShowing = true
    }
    
    deinit {
        self.isShowing = false
    }
    
    private func setupViews() {
        self.view.addSubview(self.coverView)
        self.coverView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        self.view.addSubview(self.panelView)
        self.panelView.snp.makeConstraints { (make) in
            make.left.equalTo(45)
            make.right.equalTo(-45)
            make.centerX.equalTo(self.view)
            make.centerY.equalTo(self.view)
        }
        
        self.panelView.addSubview(self.titleLabel)
        self.titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.panelView).offset(15)
            make.left.equalTo(self.panelView).offset(10)
            make.right.equalTo(self.panelView).offset(-10)
        }
        
        self.panelView.addSubview(self.preferredMoneyLabel)
        self.preferredMoneyLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.panelView).offset(10)
            make.right.equalTo(self.panelView).offset(-10)
            make.top.equalTo(self.titleLabel.snp.bottom).offset(15)
        }
        
        self.panelView.addSubview(self.actualMoneyLabel)
        self.actualMoneyLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.panelView).offset(10)
            make.right.equalTo(self.panelView).offset(-10)
            make.top.equalTo(self.preferredMoneyLabel.snp.bottom).offset(10)
        }
        
       // self.panelView.addSubview(self.reasonLabel)
//        self.reasonLabel.snp.makeConstraints { (make) in
//            make.left.equalTo(self.panelView).offset(10)
//            make.right.equalTo(self.panelView).offset(-10)
//            make.top.equalTo(self.actualMoneyLabel.snp.bottom).offset(10)
//        }
        
        let horizontalLine1 = UIView()
        horizontalLine1.backgroundColor = UIColor(red: 243/255, green: 243/255, blue: 243/255, alpha: 1)
        self.panelView.addSubview(horizontalLine1)
        horizontalLine1.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.panelView)
        make.top.equalTo(self.actualMoneyLabel.snp.bottom).offset(10)
            make.height.equalTo(1)
        }
        
        self.panelView.addSubview(self.okButton)
        self.okButton.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.panelView)
            make.top.equalTo(horizontalLine1.snp.bottom)
            make.bottom.equalTo(self.panelView).offset(-5)
        }
    }
    
    private func updateViews() {
        self.preferredMoneyLabel.attributedText = self.preferredMoneyLabelString
        self.actualMoneyLabel.attributedText = self.actualMoneyLabelString
       // self.reasonLabel.text = self.reasonLabelString
    }
    
    @objc private func doOkButtonAction() {
        self.dismiss(animated: true, completion: nil)
    }
    
    private func analysis(_ dict: [String: Any]) {
        if let preferredMoney = dict["ProtocolSalary"] {
            self.preferredMoney = "\(preferredMoney)"
        }
        
        if let actualMoney = dict["RealPaySalary"] {
            self.actualMoney = "\(actualMoney)"
        }
        self.reason = dict["DeductionReason"] as? String
    }
}

extension ETSalaryCalculationAlertController: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SalaryCalculationControllerTransitionPresent()
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SalaryCalculationControllerTransitionDismiss()
    }
}

class SalaryCalculationControllerTransitionPresent: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromView = transitionContext.view(forKey: .from)
        let toVc = transitionContext.viewController(forKey: .to) as! ETSalaryCalculationAlertController
        let container = transitionContext.containerView
        container.addSubview(toVc.view)
        
        let panelView = toVc.panelView
        let coverview = toVc.coverView
        coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        panelView.alpha = 0.3
        panelView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
        UIView.animate(withDuration:0.1, animations: {
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.3)
            panelView.transform = CGAffineTransform.identity
            panelView.alpha = 1
        }) { (finish) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            toVc.view.addSubview(fromView!)
            toVc.view.sendSubview(toBack: fromView!)
        }
    }
}

class SalaryCalculationControllerTransitionDismiss: NSObject,UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromVc = transitionContext.viewController(forKey: .from) as! ETSalaryCalculationAlertController
        
        //        let panelView = fromVc.panelView
        let coverview = fromVc.coverView
        UIView.animate(withDuration: 0.1, animations: {
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        }) { (_) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
}

